﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.SessionState;
using System.Web;
using LotteryVote.Entity;
using LotteryVote.Logic.Exceptions;
using LotteryVote.Utility;

namespace LotteryVote.Logic.Web
{
    public abstract class BaseHandler : IExecutable, IHttpHandler, IRequiresSessionState
    {
        private LoginFacade _loginFacade;
        private User _user;

        protected virtual SystemRole IdentityRole
        {
            get
            {
                return SystemRole.Guest;
            }
        }

        protected LoginFacade LoginFacade
        {
            get
            {
                if (_loginFacade == null)
                    _loginFacade = new LoginFacade();
                return _loginFacade;
            }
        }
        public User CurrentUser
        {
            get
            {
                if (_user == null)
                    _user = LoginFacade.GetCurrentUser();
                return _user;
            }
        }
        public bool IsLogin
        {
            get { return LoginFacade.IsLogin; }
        }


        public bool IsReusable
        {
            get { throw new NotImplementedException(); }
        }

        public void ProcessRequest(HttpContext context)
        {
            Execute(() =>
            {
                CheckRole();
                Process(context);
            });
        }
        public abstract void Process(HttpContext context);

        protected void CheckRole()
        {
            if (!IsLogin)
                throw new NoPermissionException("");
            if (CurrentUser.Role > IdentityRole)
                throw new NoPermissionException("");
        }

        public void Execute(Action action)
        {
            try
            {
                action();
            }
            catch (Exception ex)
            {
                LogConsole.Error(ex);
                HttpContext.Current.Response.Write(ex.Message);
            }
        }


        public T Execute<T>(Func<T> action)
        {
            try
            {
                return action();
            }
            catch (Exception ex)
            {
                LogConsole.Error(ex);
                HttpContext.Current.Response.Write(ex.Message);
            }
            return default(T);
        }
    }
}
